package com.redispro.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @Auther: 李 力
 * @Date: 2024/11/25
 * @Description: com.redispro.utils
 * @version: 1.0
 */
@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;


    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit timeUnit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R, T> R queryWithPa(String keyPrefix, T queryParam, Class<R> type, Function<T, R> dbBack, Long time, TimeUnit timeUnit) {
        String key = keyPrefix + queryParam;
        String json = redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        if (json != null) {
            return null;
        }
        R apply = dbBack.apply(queryParam);
        if (apply == null) {
            redisTemplate.opsForValue().set(key, "", 10, TimeUnit.MINUTES);
            return null;
        }
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(apply), time, timeUnit);
        return apply;
    }
}
